﻿using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WebApi.Entities;

namespace WebApi.DbContexts;
public class AppDbContext:DbContext
{

    public AppDbContext()
    {
            
    }
    public AppDbContext( DbContextOptions<AppDbContext> options) : base(options)
    {
      
    }

    public DbSet<Demo> Demo { get; set; }

    public DbSet<User> User { get; set; }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        if (!optionsBuilder.IsConfigured)
        {
            var connectstring = Db.ConnectString;

            optionsBuilder
                 .LogTo(Console.WriteLine, (_, level) => level == LogLevel.Information)
                 .EnableSensitiveDataLogging()
                .UseSqlServer(connectstring, provideroptions => { provideroptions.EnableRetryOnFailure(); });

            base.OnConfiguring(optionsBuilder);
        }
    
    }


    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {

        modelBuilder.Entity<User>().OwnsOne(x => x.Address, e =>
        {
            e.ToJson();
            e.OwnsMany(x => x.Phones);
        });
            

        modelBuilder.Entity<Demo>().OwnsMany(x => x.Tags, e =>
        {
            e.ToJson();
        });


        //SeedData(modelBuilder);


        base.OnModelCreating(modelBuilder);
    }


    private void SeedData(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<User>().HasData(
           new User()
           {
               Id = Guid.Parse("06bbe74f-992a-45da-9d96-b79082d27f10"),
               Name = "Henry",
               Address = new Address()
               {
                   City = "shenzhen",
                   Phones = new List<Phone>
                   {
                       new Phone { Number = "13232467311" },
                       new Phone { Number = "13232467322" }
                   },

               }
           });





        modelBuilder.Entity<Demo>().HasData
            (
                new Demo
                {
                    Id = Guid.Parse("06bbe74f-992a-45da-9d96-b79082d27f97"),
                    Name = "T1",
                    Tags = new List<Tag> {
                        new Tag { Value = "C#"},
                        new Tag { Value = "C++"},
                    }
                },

                new Demo
                {
                    Id = Guid.Parse("06bbe74f-992a-45da-9d96-b79082d27f98"),
                    Name = "T2",
                    Tags = new List<Tag> {
                        new Tag { Value = "Python"},
                        new Tag { Value = "java"},
                    }
                }

            );


    }
}
